/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

/**
 * Service that dispatches actions to Action classes
 */
public class ActionService extends IntentService {
	
	private final static String TAG = SolidalApp.TAG + " Endpoints";

	public ActionService() {
		super("Endpoints Service");
	}	
		
	@Override
	protected void onHandleIntent(Intent intent) {
				
		try {
			
			SolidalApp app = (SolidalApp) getApplicationContext();
			
			@SuppressWarnings("unchecked")
			Class<? extends Action> actionClass = (Class<? extends Action>) 
					Class.forName(getClass().getPackage().getName()+".actions."+intent.getAction());
			
			Intent localIntent = null;
			try {
				Action action = app.putAction(actionClass);
				if (action!=null) {
					localIntent = action.init(this, intent).getIntent();
//					Log.i(TAG, "Executing: "+action.getAction());
					action.execute();
//					Log.i(TAG, "Executed: "+action.getAction());
				} else {
					Log.i(TAG, "Action already executing: "+actionClass.getSimpleName());
					return;
				}
			} catch(Exception e) {
				Log.e(TAG+" "+actionClass.getSimpleName(),
						"Service Error", e);
				localIntent.putExtra(Constants.ERROR, e.getMessage());
			}
			
			Log.d(SolidalApp.TAG+" "+actionClass.getSimpleName(), 
					"Broadcasting: "+localIntent+"\n"+EndpointsUtils.toString(localIntent.getExtras()));
			sendBroadcast(localIntent);
			
		} catch(ClassNotFoundException e) {
			Log.w(SolidalApp.TAG, "No action for: "+this);
		}
		
	}
	
	@Override
	public void onDestroy() {
		Log.d(TAG, "Destroy service");
		super.onDestroy();
	}
	
}
